package Scuttlebutt;

import java.lang.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import javax.swing.*;

	
public class NodeTransferHandler extends TransferHandler{
	private DataFlavor nodeFlavor = null;
	boolean shouldRemove = false;
	public NodeTransferHandler(){
		try{
			nodeFlavor = new DataFlavor("application/node");
			nodeFlavor.setHumanPresentableName("My node flavor");
		}catch(java.lang.ClassNotFoundException e){
			System.err.println(e);
		}
	}
	
	public boolean importData(JComponent c, Transferable t) {
		
        if (!canImport(c, t.getTransferDataFlavors())) {
            return false;
        }
        return true;
	}
	
    public boolean canImport(JComponent c, DataFlavor[] flavors) {
        for (int i = 0; i < flavors.length; i++) {
            if (nodeFlavor.equals(flavors[i])) {
                return true;
            }
        }
        return false;
    }
    //Create a Transferable implementation that contains the
    //selected text.
    protected Transferable createTransferable(JComponent c) {
	    JTree source = (JTree) c;
	    shouldRemove = false;
        Object o = source.getLastSelectedPathComponent();	        
        
        return new NodeTransferable(o);
    }
    public int getSourceActions(JComponent c) {
        return COPY_OR_MOVE;
    }

    /**
     * Does the flavor list have a string flavor?
     */
    protected boolean hasNodeFlavor(DataFlavor[] flavors) {
        for (int i = 0; i < flavors.length; i++) {
            if (nodeFlavor.equals(flavors[i])) {
                return true;
            }
        }
        return false;
    }

	class NodeTransferable implements Transferable {
    	Object node = null;
    	NodeTransferable(Object node){
	    	this.node = node;
    	}
        public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
            if (!isDataFlavorSupported(flavor)) {
                throw new UnsupportedFlavorException(flavor);
            }
            return node;
        }

        public DataFlavor[] getTransferDataFlavors() {
            return new DataFlavor[] { nodeFlavor };
        }

        public boolean isDataFlavorSupported(DataFlavor flavor) {
            return nodeFlavor.equals(flavor);
        }
   	}
}


